package com.zbcz.crm.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zbcz.crm.CrmApplication
import com.zbcz.crm.bean.Accessories
import com.zbcz.crm.network.CrmApi
import com.zbcz.crm.network.RetrofitManager
import com.zbcz.crm.sp.SharedPreferencesManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AccessQueryViewModel : ViewModel() {
    private val mApi = RetrofitManager.getRetrofit().create(CrmApi::class.java)


    val mResult: MutableLiveData<List<Accessories>?> = MutableLiveData()

    fun queryAccessoiesList(
        accessoriesName: String
    ) {
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                val result = queryAccessoiesSuspend(accessoriesName)
//                    ?.filter {
//                    if (!TextUtils.isEmpty(accessoriesName)) {
//                        it.accessoryName?.contains(accessoriesName) == true
//                    } else {
//                        true
//                    }
                //}
                mResult.postValue(result)
            }
        }
    }

    private suspend fun queryAccessoiesSuspend(
        accessoriesName: String
    ): List<Accessories>? {
        try {
            val result = mApi?.queryProductAccessory(
                token = SharedPreferencesManager.getToken(CrmApplication.mApplication),
                accessoriesName
            )
            if (result?.success == true) {
                return result.result?.records
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}